package com.wen.jwtdemo.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;


public class JwtUtils {

    private final static String key = "thisiskey";
    //封装一些jwt的常用方法
    public static String getToketn(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,120);
        JWTCreator.Builder builder = JWT.create();   //得到构建对象
        //往里面填充负荷里面需要记录的信息   头部信息有默认的   我们如果想要指定也可以
        map.forEach((k,v) -> builder.withClaim(k,v));
        //设置过期时间
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(key)).toString();
    }

    public static DecodedJWT verify(String token){
        //用来验证token是否还是有效的
        return JWT.require(Algorithm.HMAC256(key)).build().verify(token);
    }

}
